﻿using DGZImp.Core.Services;
using DGZImp.MdsProject.Devices.Base;
using DGZImp.MdsProject.Devices;
using DGZImp.MdsProject.Devices.Models;
using Microsoft.AspNetCore.Hosting.Server;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DGZImp.Core.Exceptions;
using DGZImp.MdsProject.Devices.Entities;
using static Nomad.Iot.Profinet.Knx.KnxCode;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;

namespace DGZImp.MdsProject.Helper
{
    /// <summary>
    /// SCADA对接辅助类
    /// </summary>
    public static class ScadaHelper
    {
        private static string url = "http://10.16.4.11";
        private static string username = "wms";
        private static string password = "AtbfWms123";
        private static string pk_entity = "411b6608-9fc4-4d2b-945e-d38f351f000c";

        public static HttpClient Client
        {
            get
            {
                var c = ServiceProviderAccessor.ServiceProvider.GetService<IHttpClientFactory>().CreateClient();
                c.BaseAddress = new Uri(url);
                return c;
            }
        }

        public static async Task<string> GetSession()
        {
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("SLOGINNAME", username),
                new KeyValuePair<string, string>("SPASSWORD", password)
            });
            var res = await Client.PostAsync("/IMR/Auth", content);
            var resStr = await res.Content.ReadAsStringAsync();
            var resObj = JObject.Parse(resStr);
            if (resObj["Exception"] == null || resObj["Exception"].ToString() == "")
            {
                return resObj["Value"]["PK"].ToString();
            }
            else
            {
                throw new AppException(resObj["Exception"]["Message"].ToString());
            }
        }

    }

}
